durations
![NPM version](https://img.shields.io/npm/v/durations.svg)
Compatibilty
Both Node.js and browsers are supported by durations
. When using Node.js, the nanosecond-granulatiry process.hrtime()
function is used. The best substitution is selected when in the browser such that consistency is maintained even if time granularity cannot be.
Installation
npm install --save durations
Methods
The following functions are exported:
duration(nanoseconds)
- constructs a new Durationnanos(nanoseconds)
- constructs a new Durationmicros(microseconds)
- constructs a new Durationmillis(milliseconds)
- constructs a new Durationseconds(seconds)
- constructs a new Durationstopwatch()
- constructs a new Stopwatch (stopped)time(function)
- times a function synchronouslytimeAsync(function(callback))
- times a function asynchronouslytimePromised(function())
- times a promise-returning function
Duration
Represents a duration with nanosecond granularity, and provides methods
for converting to other granularities, and formatting the duration.
Methods
format()
- human readable string representing the durationnanos()
- duration as nanosecondsmicros()
- duration as microsecondsmillis()
- duration as millisecondsseconds()
- duration as secondsminutes()
- duration as minuteshours()
- duration as hoursdays()
- duration as days
const {duration} = require('durations')
const nanoseconds = 987654321
console.log("Duration is", duration(nanoseconds).format())
console.log(`Duration is ${duration(nanoseconds)}`)
Stopwatch
A nanosecond granularity (on Node.js) stopwatch with chainable control methods,
and built-in formatting.
Stopwatch Methods
start()
- start and return the stopwatch (no-op if already running)stop()
- stop and return the stopwatch (no-op if not running)reset()
- reset to zero elapsed time and return the stopwatch (implies stop)duration()
- fetch the elapsed time as a DurationisRunning()
- is the stopwatch running (true
/false
)
const {stopwatch} = require('durations')
const watch = stopwatch()
watch.stop()
watch.start()
watch.reset()
console.log(`${watch.duration().seconds()} seconds have elapsed`)
console.log(`${watch} have elapsed`)
Timer
Times the execution of a function, and returns the duration.
const {time: timeSync, timeAsync} = require('durations')
const someFunction = () => {
let count = 0
while (count < 1000000) {
count++
}
console.log(`Count is: ${count}`)
}
console.log(`Took ${timeSync(someFunction)} to do something`)
const someOtherFunction = next => {
someFunction()
next()
}
timeAsync(someOtherFunction, duration => {
console.log(`Took ${duration} to do something else.`)
})
const somePromisedOp = () => {
return new Promise((resolve) => {
someFunction()
resolve()
})
}
timePromised(somePromisedOp)
.then(duration => {
console.log(`Took ${duration} to keep promise.`)
})